/**
 * 
 */
package com.java.controller.front;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Pattern.Flag;

import org.apache.commons.lang3.StringUtils;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.java.entity.User;
import com.java.service.impl.UserServiceImpl;
import com.java.utils.md5Utils;

import net.sf.json.JSON;
import net.sf.json.JSONArray;

/**
* @author Kidney
* 创建时间：2019年2月25日 下午5:35:15
* Description:
*/
/**
 * @author KIDNEY
 *
 */

@Controller
public class UserController {
	@Autowired
	UserServiceImpl us;

	@RequestMapping("login")
	public ModelAndView login(@RequestParam("userId") Integer userId, @RequestParam("password") String password,
			HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {

		HttpSession session = request.getSession();

		User user = new User();
		user.setId(userId);
		// md5
		String p1 = md5Utils.md5(password);
		user.setPassword(p1);

		// Session中存好的验证码数值
		String piccode = (String) request.getSession().getAttribute("piccode");
		// 前端用户输入的验证码值
		String verifycode = request.getParameter("verifycode");

		String newV = verifycode.toUpperCase();

		User result = us.login(user, response);

		if (result != null && newV.equals(piccode)) {
			ModelAndView mAndView = null;
			// 登录之前地址
			String callback = (String) session.getAttribute("callback");
			session.removeAttribute("callback"); // 获取之后移除
			// 基本路径
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath();

			if (StringUtils.isNotBlank(callback) && userId == 1) {
				System.out.println("admin");
				String[] urls = callback.split(basePath);
				if (urls.length == 2 && StringUtils.isNotBlank(urls[1])) {
					mAndView = new ModelAndView("redirect:" + urls[1]);
				} else {
					mAndView = new ModelAndView(" /WEB-INF/user_controller.jsp");
				}
			} else if (userId == 1) {
				mAndView = new ModelAndView("/WEB-INF/user_controller.jsp");
			}

			if (StringUtils.isNotBlank(callback) && (userId == 1) == false) {
				String[] urls = callback.split(basePath);
				if (urls.length == 2 && StringUtils.isNotBlank(urls[1])) {
					mAndView = new ModelAndView("redirect:" + urls[1]);
				} else {
					mAndView = new ModelAndView("/WEB-INF/student.jsp");
					User user2 = new User();
					user2 = us.selectByPrimaryKey(userId);
					mAndView.getModel().put("user", user2);

				}
			} else if ((userId == 1) == false) {
				mAndView = new ModelAndView("/WEB-INF/student.jsp");
				User user2 = new User();
				user2 = us.selectByPrimaryKey(userId);
				mAndView.getModel().put("user", user2);

			}

			session.setAttribute("user", result); // 登录成功之后加入session中
			redirectAttributes.addFlashAttribute("user", result);

			return mAndView;
		} else {
			return new ModelAndView("/index.jsp");
		}
	}

	@RequestMapping("logout")
	public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mAndView = new ModelAndView("redirect:/index.jsp");
		us.logout(request, response);
		return mAndView;
	}

	@RequestMapping("search")
	@ResponseBody
	public ModelAndView test1(Integer id, String name, Integer gender, Integer classId) {
		ModelAndView mav = new ModelAndView();

		User user = new User();
		user.setClassId(classId);
		user.setGender(gender);
		user.setName(name);
		user.setId(id);
		List<User> list = us.selectByCondition(user);

		mav.setViewName("/pages/admin.jsp");
		mav.getModel().put("user", list);
		return mav;
	}

	@RequestMapping("delete")
	@ResponseBody
	public int delete(Integer id) {
		return us.deleteByPrimaryKey(id);
	}

	@RequestMapping("insert")
	@ResponseBody
	public ModelAndView insert(String name, Integer gender, String project, String date, String email, Integer classId,
			String password) {
		ModelAndView mav = new ModelAndView();
		User user = new User();
		user.setClassId(classId);
		user.setGender(gender);
		user.setName(name);
		user.setProjectName(project);
		user.setDate(date);
		user.setEmail(email);
		user.setPassword(md5Utils.md5(password));
		int flag1 = us.insertSelective(user);

		if (flag1 == 1) {
			List<User> users = us.selectAll();
			mav.setViewName("/pages/admin.jsp");
			mav.getModel().put("user", users);
		} else {

			mav.getModel().put("status", "输入错误");
		}

		return mav;
	}

	@RequestMapping("user_update")
	public ModelAndView userUpdate(String date, String email, String password, Integer id) throws ParseException {

		ModelAndView mav = new ModelAndView();
		User user = new User();

		if ("".equals(password)) {
		} else {

			user.setPassword(md5Utils.md5(password));
		}
		System.out.println(date);

		user.setDate(date);
		user.setEmail(email);
		user.setId(id);
		mav.getModel().put("status", "1111");
		mav.setViewName("/WEB-INF/student.jsp");
		int flag1 = us.updateByPrimaryKeySelective(user);

		if (flag1 == 1) {
			user = us.selectByPrimaryKey(id);
			mav.getModel().put("user", user);
			mav.getModel().put("status", "修改成功");
			mav.setViewName("/WEB-INF/student.jsp");
		} else {
			mav.getModel().put("status", "修改失败");
			mav.setViewName("/WEB-INF/student.jsp");
		}

		return mav;
	}

	@RequestMapping("update")
	@ResponseBody
	public int update(String name, Integer gender, String project, String date, String email, Integer classId,
			Integer id, String password) {

		User user = new User();
		user.setId(id);
		user.setClassId(classId);
		user.setGender(gender);
		user.setName(name);
		user.setProjectName(project);
		user.setDate(date);
		user.setEmail(email);
		user.setPassword(md5Utils.md5(password));
		return us.updateByPrimaryKeySelective(user);
	}

	// 插入图片信息
	@RequestMapping("image_insert")
	@ResponseBody
	public ModelAndView insertImage(Integer id, HttpServletRequest request, MultipartRequest files)
			throws IllegalStateException, IOException {

		ModelAndView mav = new ModelAndView();
		mav.setViewName("/WEB-INF/student.jsp");

		int flag = 0;
		Map<String, MultipartFile> filesMap = files.getFileMap();

		Set<String> keyset = filesMap.keySet();
		for (String key : keyset) {
			MultipartFile file = files.getFile(key);
			String originalFilename = file.getOriginalFilename();
			String uuid = UUID.randomUUID().toString();

			String path = request.getServletContext().getRealPath("/upload");

			String basePath = path.split("webapps")[0] + "webapps\\upload";
			// System.out.println(basePath);

			File fileUpload = new File(basePath);
			if (!fileUpload.exists()) {// 经过此方法后,upload文件夹一定是存在的
				fileUpload.mkdir();
			}



			// 保存文件
			String filePath = basePath + "\\" + uuid + originalFilename;
			file.transferTo(new File(filePath));


			String fileName = uuid + originalFilename;

			String url = "/upload/" + fileName;

		
			User user = new User();
			user = us.selectByPrimaryKey(id);
			System.out.println(id);
			user.setImage(url);
			user.setId(id);
			System.out.println(url);
			
			flag =us.updateByPrimaryKeySelective(user);
			System.out.println(flag);
			if(flag==1){
				user = us.selectByPrimaryKey(id);
				
				mav.getModel().put("user", user);
				mav.getModel().put("status", "照片添加成功");
			}else{
				
				mav.getModel().put("status", "照片添加失败");
			}
		}

		return mav;
	}
	
	
	@RequestMapping("test2")
	@ResponseBody
	public int test2() {

		User user = new User();
		user = us.selectByPrimaryKey(30);
		
		us.updateByPrimaryKeySelective(user);
		return us.updateByPrimaryKeySelective(user);
	}
	
	
	
	

	@RequestMapping("all")
	@ResponseBody
	public ModelAndView all() {
		ModelAndView mav = new ModelAndView();
		List<User> user = us.selectAll();
		mav.setViewName("/pages/admin.jsp");
		mav.getModel().put("user", user);
		return mav;
	}

	@RequestMapping("all1")
	@ResponseBody
	public String all1() {

		List<User> user = us.selectAll();

		JSONArray json = JSONArray.fromObject(user);

		return json.toString();
	}

}
